<template>
  <div class="login">
    <div class="box">
      <h2>协同系统管理平台</h2>
      <el-form
          size="small"
          ref="formRef"
          style="max-width: 600px"
          :model="formData"
          status-icon
          :rules="rules"
          label-width="60px"
      >

       

        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" style="width: 300px;"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" style="width: 300px;" type="password"/>
        </el-form-item>

       

         <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" style="width: 300px;" placeholder="请选择类型" @change="fetchNames">
            <el-option label="酒店" value="hotel"/>
            <el-option label="旅游商" value="travel"/>
            <el-option label="平台" value="platform"/>
          </el-select>
        </el-form-item>

        <el-form-item label="名称" prop="typeNameId">
          <el-select v-model="formData.typeNameId" style="width: 300px;" placeholder="请选择名称">
            <el-option
                v-for="option in names"
                :key="option.id"
                :label="option.name"
                :value="option.id"
            />
          </el-select>
        </el-form-item>

         <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)">登录</el-button>
          <el-button @click="resetForm(formRef)">取消</el-button>
          <el-button type="success" @click="Settled">入驻</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
//导入组合式api
import {reactive, ref, onMounted} from 'vue'
//导入路由器
import {useRouter} from "vue-router";
import useUser from "../store/user.ts";
import { ElNotification } from 'element-plus'
//导入element-plus的类型
import type {FormInstance, FormRules} from 'element-plus'
//导入请求api
import {$Login, $getOne, $platFormName} from "../api/admin";

//返回路由器对象
const router = useRouter()
//获取user全局状态
const userStore = useUser()

//定义一个ref对象绑定表单
const formRef = ref<FormInstance>()

//表单数据
const formData = reactive({
  type: '',
  typeNameId: '',
  username: '',
  password: ''
})

//名称列表
const names = ref<{id: number, name: string}[]>([]);

//获取名称列表
const fetchNames = async () => {
  if (formData.type) {
    const ret = await $platFormName({type: formData.type});
    if (ret.code === 2001) {
      names.value = ret.data.map((item:any) =>({
        id:item.id,
        name:item.hotelName || item.travelName
      }));
      formData.typeNameId = ''; 
    }else{
      ElNotification({
            title: '通知',
            message: '服务器异常，请联系管理员！',
            type: 'error',
        });
    }
  }
}

//注册
const Settled = () => {
  // 注册逻辑
  router.push('/HotelSettled');
}

//验证账号
const validateLoginId = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}


//验证密码
const validateLoginPwd = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

//验证类型
const validateType = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入类型'))
  } else {
    callback()
  }
}

const validateTypeNameId = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入类型'))
  } else {
    callback()
  }
}


//验证对象
const rules = reactive<FormRules<typeof formData>>({
  username: [{validator: validateLoginId, trigger: 'blur'}],
  password: [{validator: validateLoginPwd, trigger: 'blur'}],
  type: [{validator: validateType, trigger: 'blur'}],
  typeNameId: [{validator: validateTypeNameId, trigger: 'blur'}]
})

//提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      const ret = await $Login(formData)
      if (ret) {
        let data = await $getOne({username: formData.username,type:formData.type, typeNameId: formData.typeNameId})
        console.log(data);
        
        userStore.setUser(data.data)
        //将用户信息存储到浏览器缓存
        sessionStorage.setItem('user', JSON.stringify(data.data))
        if (formData.type === 'platform') {
          router.push('/Platform')
        } else if(formData.type === 'hotel') {
          
          router.push('/index')
        } else{
          
          router.push('/travel')
        }
      }
    } else {
      console.log('error submit!')
    }
  })
}

//重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  if(userStore.user != null){
    if (userStore.user.type === 'platform') {
      router.push('/Platform')
    }else if(userStore.user.type === 'hotel'){
      router.push('/index')
    }else if(userStore.user.type === 'travel'){
      router.push('/travel')
    }
  }
  
})



// const hotelNames = ref<hotel[]>([]);

// onMounted(async () => {
//   try {
//     const ret = await $hotelNames();  // 假设 $hotelNames 是一个返回 Promise 的函数
//     if (ret) {
//       if (ret.code === 2001) {
//         hotelNames.value = ret.t;  // 假设 ret.t 是一个符合 Hotel[] 类型的数据
//       } else {
//         alert(ret.message);
//       }
//     }
//   } catch (error) {
//     console.error('Failed to fetch hotel names:', error);
//   }
// });


</script>

<style scoped lang="scss">
.login {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to bottom, #142334, #6894c7);
  display: flex;
  justify-content: center;
  align-items: center;

  .box {
    width: 500px;
    padding: 20px;
    border: 1px solid #fff;

    h2 {
      color: white;
      font-size: 30px;
      text-align: center;
      margin-bottom: 20px;
      padding-right: 35px;
      font-family: gong;
    }

    //scss 深度设置

    ::v-deep .el-form-item__label {
      color: white;
    }

  }
}
</style>